package algebra.op;

import java.util.HashSet;
import java.util.Set;

import option.QueryKeywords;

import utils.Display;

import kb.DescriptionLogicsKB;
import entities.concept.Concept;
import entities.role.Role;

public class SelectionOP extends AlgebraicOP {
	private final AlgebraicOP sub;
	private final Concept c;
	private final DescriptionLogicsKB kb;

	// public SelectionOP(AlgebraicOP sub, Concept c) {
	// super();
	// this.sub = sub;
	// this.c = c;
	// this.kb = null;
	// }

	public SelectionOP(AlgebraicOP sub, Concept c, DescriptionLogicsKB kb) {
		super();
		this.sub = sub;
		this.c = c;
		this.kb = kb;
	}

	@Override
	public boolean isPure() {
		return sub.isPure();
	}

	public AlgebraicOP getSubquery() {
		return this.sub;
	}

	public Concept getSelectionCondition() {
		return this.c;
	}

	@Override
	public String toString() {
		return Display.QSELECTIONUNICODE + "["
				+ (this.getPlanEvalKB() == null ? " ]" : "K]") + "["
				+ this.c.toString() + "](" + this.sub.toString() + ")";
	}

	@Override
	public String toSerializedString() {
		return " (" + QueryKeywords.QSELECT + "["
				+ (this.getPlanEvalKB() == null ? " ]" : "K]") + " "
				+ this.c.toSerializedString() + " "
				+ this.sub.toSerializedString() + ") ";
	}

	@Override
	public DescriptionLogicsKB getPlanEvalKB() {
		return this.kb;
	}

	// public void setPlanEvalKB(DescriptionLogicsKB kb){
	// this.kb = kb;
	// }

	@Override
	public Set<Role> extractFeatures() {
		Set<Role> fs = new HashSet<Role>();
		fs.addAll(this.c.extractFeatures());
		fs.addAll(this.sub.extractFeatures());
		return fs;
	}

	@Override
	public Set<String> extractConstants() {
		Set<String> ks = new HashSet<String>();
		ks.addAll(this.c.extractConstants());
		ks.addAll(this.sub.extractConstants());
		return ks;
	}

	@Override
	public boolean isLeaf() {
		return false;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((c == null) ? 0 : c.hashCode());
		result = prime * result + ((kb == null) ? 0 : kb.hashCode());
		result = prime * result + ((sub == null) ? 0 : sub.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof SelectionOP))
			return false;
		SelectionOP other = (SelectionOP) obj;
		if (c == null) {
			if (other.c != null)
				return false;
		} else if (!c.equals(other.c))
			return false;
		if (kb == null) {
			if (other.kb != null)
				return false;
		} else if (!kb.equals(other.kb))
			return false;
		if (sub == null) {
			if (other.sub != null)
				return false;
		} else if (!sub.equals(other.sub))
			return false;
		return true;
	}

	@Override
	public SelectionOP getKFreeVersion() {
		return new SelectionOP(sub, c, null);
	}

}
